/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.sistemafacturacion.gco.ui;

import com.jjsoft.sistemafacturacion.gco.dao.GenericController;
import com.jjsoft.sistemafacturacion.gco.mdl.Articulo;
import com.jjsoft.sistemafacturacion.gco.mdl.Cliente;
import com.jjsoft.sistemafacturacion.gco.mdl.Detallefactura;
import com.jjsoft.sistemafacturacion.gco.mdl.Factura;
import com.jjsoft.sistemafacturacion.gco.ngc.ArticuloManager;
import com.jjsoft.sistemafacturacion.gco.ngc.ClienteManager;
import com.jjsoft.sistemafacturacion.gco.ngc.FacturaManager;
import com.jjsoft.sistemafacturacion.gco.util.CNumeros;
import com.jjsoft.sistemafacturacion.gco.util.CSelecciones;
import com.jjsoft.sistemafacturacion.gco.util.DBRestore;
import com.jjsoft.sistemafacturacion.gco.util.MiModelo;
import com.jjsoft.sistemafacturacion.gco.util.Validacion;
import com.jjsoft.sistemafacturacion.gco.util.configuraciones;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

/**
 *
 * @author johnny
 */
public class VPrincipal extends javax.swing.JFrame {

    /**
     * Creates new form VPrincipal
     */
    Articulo objArt;
    MiModelo modelo = new MiModelo();
    JTextField texto;
    Date d = new Date();
    Factura factura;
    ArticuloManager am = new ArticuloManager();
    private static VPrincipal instance;

    public static VPrincipal getInstance() {
        if (instance == null) {
            instance = new VPrincipal();
        }
        return instance;
    }
    
    public VPrincipal() {
        initComponents();
        cmdAgregar.setMnemonic(KeyEvent.VK_A);
        cmdGuardar.setMnemonic(KeyEvent.VK_G);
        cmdQuitar.setMnemonic(KeyEvent.VK_Q);
        this.txtFecha.setText(this.d.getDate() + "-" + (this.d.getMonth() + 1) + "-" + (this.d.getYear() + 1900));
        String[] identificadores = {"CANT", "DESCRIPCION", "P. UNIT", "V. VENTA"};
        this.modelo.setColumnIdentifiers(identificadores);
        this.dtgFactura.setModel(this.modelo);
        this.dtgFactura.getColumn("CANT").setPreferredWidth(30);
        this.dtgFactura.getColumn("DESCRIPCION").setPreferredWidth(330);
        this.dtgFactura.getColumn("P. UNIT").setPreferredWidth(50);
        this.dtgFactura.getColumn("V. VENTA").setPreferredWidth(50);
        setTitle("Sistema Ventas " + configuraciones.getInstance().getConfiguracion().getNombreLocal());
        this.lblLocal.setText(configuraciones.getInstance().getConfiguracion().getNombreLocal());
        this.lblDireccion.setText("Direccion: " + configuraciones.getInstance().getConfiguracion().getDireccion()+"    Telefono: " + configuraciones.getInstance().getConfiguracion().getTelefono()+"    Propietario: " + configuraciones.getInstance().getConfiguracion().getNombreDuenio());
        this.lblUsuario.setText("Usuario: " + configuraciones.getInstance().getUsuario().getNombre());
        cmdBuscar.setVisible(false);
        factura = new Factura();
        factura.setDetallefacturaList(new ArrayList());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mnuAcciones = new javax.swing.JPopupMenu();
        mnuQuitar = new javax.swing.JMenuItem();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtCliente = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtCedula = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtFecha = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        txtNumero = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtGuia = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgFactura = new javax.swing.JTable();
        txtCodigo = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        cmdAgregar = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        txtSubtotal = new javax.swing.JTextField();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        txtSubtotalD = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        txtIVA = new javax.swing.JTextField();
        cmdQuitar = new javax.swing.JButton();
        cmdGuardar = new javax.swing.JButton();
        txtDescuento = new javax.swing.JSpinner();
        jLabel16 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();
        txtCantidad = new javax.swing.JSpinner();
        jLabel17 = new javax.swing.JLabel();
        lblLocal = new javax.swing.JLabel();
        lblDireccion = new javax.swing.JLabel();
        jSeparator2 = new javax.swing.JSeparator();
        lblUsuario = new javax.swing.JLabel();
        txtProducto = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        cmdBuscarCliente = new javax.swing.JButton();
        cmdBuscar = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnuMantenimientos = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        mnuManArticulos = new javax.swing.JMenuItem();
        mnuManProveedores = new javax.swing.JMenuItem();
        mnuReportes = new javax.swing.JMenu();
        mnuStockMinimo = new javax.swing.JMenuItem();
        mnuStock = new javax.swing.JMenuItem();
        mnuFacturas = new javax.swing.JMenu();
        mnuBuscarFacturaNumero = new javax.swing.JMenuItem();
        mnuBuscarFacturaCliente = new javax.swing.JMenuItem();
        cmdBuscarFacturaFecha = new javax.swing.JMenuItem();
        mnuRepVentasFechas = new javax.swing.JMenuItem();
        mnuSistema = new javax.swing.JMenu();
        mnuAjustes = new javax.swing.JMenuItem();
        mnuUsuarios = new javax.swing.JMenuItem();
        mnuReindexar = new javax.swing.JMenuItem();
        mnuRespaldar = new javax.swing.JMenuItem();

        mnuQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        mnuQuitar.setText("Quitar");
        mnuQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuQuitarActionPerformed(evt);
            }
        });
        mnuAcciones.add(mnuQuitar);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("FACTURA");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(51, 51, 51));
        jLabel3.setText("Cliente:");

        txtCliente.setEditable(false);
        txtCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtClienteActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(51, 51, 51));
        jLabel4.setText("RUC / C.I:");

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(51, 51, 51));
        jLabel5.setText("Telf:");

        txtTelefono.setEditable(false);

        txtCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCedulaActionPerformed(evt);
            }
        });
        txtCedula.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCedulaKeyPressed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setForeground(new java.awt.Color(51, 51, 51));
        jLabel6.setText("Fecha de Emision:");

        txtFecha.setEditable(false);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(51, 51, 51));
        jLabel7.setText("Numero:");

        txtNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNumeroActionPerformed(evt);
            }
        });
        txtNumero.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtNumeroKeyReleased(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(51, 51, 51));
        jLabel2.setText("Direccion:");

        txtDireccion.setEditable(false);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setForeground(new java.awt.Color(51, 51, 51));
        jLabel8.setText("Guia de Remision:");

        dtgFactura.setComponentPopupMenu(mnuAcciones);
        dtgFactura.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgFactura);

        txtCodigo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCodigoActionPerformed(evt);
            }
        });
        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCodigoKeyReleased(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
        });

        jLabel9.setText("Codigo:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/search-database.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel10.setText("Cantidad:");

        jLabel11.setText("P. Unit");

        txtPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPrecioKeyReleased(evt);
            }
        });

        cmdAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/add.png"))); // NOI18N
        cmdAgregar.setText("Agregar");
        cmdAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdAgregarActionPerformed(evt);
            }
        });

        jLabel12.setText("Subtotal_0:");

        txtSubtotal.setEnabled(false);

        jLabel13.setText("Descuento:");

        jLabel14.setText("Subtotal_D:");

        txtSubtotalD.setEnabled(false);

        jLabel15.setText("IVA:");

        txtIVA.setEnabled(false);

        cmdQuitar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdQuitar.setText("    Quitar");
        cmdQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdQuitarActionPerformed(evt);
            }
        });

        cmdGuardar.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
        cmdGuardar.setText("     GUARDAR");
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });

        txtDescuento.setModel(new javax.swing.SpinnerNumberModel(0, 0, 100, 1));
        txtDescuento.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                txtDescuentoStateChanged(evt);
            }
        });

        jLabel16.setText("Total:");

        txtTotal.setEditable(false);
        txtTotal.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        txtTotal.setForeground(new java.awt.Color(255, 0, 0));

        txtCantidad.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        jLabel17.setText("%");

        lblLocal.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        lblLocal.setForeground(new java.awt.Color(0, 0, 255));
        lblLocal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblLocal.setText("jLabel9");

        lblDireccion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblDireccion.setText("jLabel11");

        lblUsuario.setText("jLabel9");

        txtProducto.setEditable(false);

        jLabel18.setText("Producto:");

        jButton2.setText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        cmdBuscarCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/1384254751_Search-Male-User.png"))); // NOI18N
        cmdBuscarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBuscarClienteActionPerformed(evt);
            }
        });

        cmdBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBuscarActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/1384333466_button_cancel.png"))); // NOI18N
        jButton3.setText("Cancelar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jMenuBar1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jMenuBar1.setForeground(new java.awt.Color(0, 0, 204));
        jMenuBar1.setMargin(new java.awt.Insets(0, 0, 0, 10));
        jMenuBar1.setPreferredSize(new java.awt.Dimension(95, 35));

        mnuMantenimientos.setText("Mantenimientos");
        mnuMantenimientos.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Clientes");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        mnuMantenimientos.add(jMenuItem1);

        mnuManArticulos.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnuManArticulos.setText("Articulos");
        mnuManArticulos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuManArticulosActionPerformed(evt);
            }
        });
        mnuMantenimientos.add(mnuManArticulos);

        mnuManProveedores.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnuManProveedores.setText("Proveedores");
        mnuManProveedores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuManProveedoresActionPerformed(evt);
            }
        });
        mnuMantenimientos.add(mnuManProveedores);

        jMenuBar1.add(mnuMantenimientos);

        mnuReportes.setText("Reportes");

        mnuStockMinimo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_M, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnuStockMinimo.setText("Stock Minimo");
        mnuStockMinimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuStockMinimoActionPerformed(evt);
            }
        });
        mnuReportes.add(mnuStockMinimo);

        mnuStock.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnuStock.setText("Stock");
        mnuStock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuStockActionPerformed(evt);
            }
        });
        mnuReportes.add(mnuStock);

        mnuFacturas.setText("Facturas");

        mnuBuscarFacturaNumero.setText("Buscar por numero");
        mnuBuscarFacturaNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuBuscarFacturaNumeroActionPerformed(evt);
            }
        });
        mnuFacturas.add(mnuBuscarFacturaNumero);

        mnuBuscarFacturaCliente.setText("Buscar por cliente");
        mnuBuscarFacturaCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuBuscarFacturaClienteActionPerformed(evt);
            }
        });
        mnuFacturas.add(mnuBuscarFacturaCliente);

        cmdBuscarFacturaFecha.setText("Buscar por fecha");
        cmdBuscarFacturaFecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBuscarFacturaFechaActionPerformed(evt);
            }
        });
        mnuFacturas.add(cmdBuscarFacturaFecha);

        mnuReportes.add(mnuFacturas);

        mnuRepVentasFechas.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnuRepVentasFechas.setText("Reporte Ventas Fecha");
        mnuRepVentasFechas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRepVentasFechasActionPerformed(evt);
            }
        });
        mnuReportes.add(mnuRepVentasFechas);

        jMenuBar1.add(mnuReportes);

        mnuSistema.setText("Sistema");

        mnuAjustes.setText("Ajustes");
        mnuAjustes.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuAjustesActionPerformed(evt);
            }
        });
        mnuSistema.add(mnuAjustes);

        mnuUsuarios.setText("Usuarios");
        mnuUsuarios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuUsuariosActionPerformed(evt);
            }
        });
        mnuSistema.add(mnuUsuarios);

        mnuReindexar.setText("Reindexar Datos");
        mnuReindexar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuReindexarActionPerformed(evt);
            }
        });
        mnuSistema.add(mnuReindexar);

        mnuRespaldar.setText("Respaldar Base de Datos");
        mnuRespaldar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRespaldarActionPerformed(evt);
            }
        });
        mnuSistema.add(mnuRespaldar);

        jMenuBar1.add(mnuSistema);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblUsuario)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel9)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel18)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtProducto)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel11)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmdAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cmdQuitar)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cmdGuardar)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButton3))
                                    .addComponent(jButton2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 319, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel16, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel14, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel15, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(txtDescuento, javax.swing.GroupLayout.DEFAULT_SIZE, 87, Short.MAX_VALUE)
                                        .addComponent(txtSubtotal)
                                        .addComponent(txtSubtotalD, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(txtIVA, javax.swing.GroupLayout.Alignment.TRAILING))
                                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jSeparator1)
                            .addComponent(jScrollPane1)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel17)
                        .addGap(29, 29, 29))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtTelefono)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtGuia, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(44, 44, 44))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cmdBuscarCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(127, 127, 127)
                                        .addComponent(cmdBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap(37, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(lblDireccion, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblLocal, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jSeparator2))
                        .addGap(44, 44, 44))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(lblLocal)
                .addGap(18, 18, 18)
                .addComponent(lblDireccion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmdBuscar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                                .addComponent(jLabel4)
                                .addComponent(txtCedula)
                                .addComponent(jLabel3)
                                .addComponent(txtCliente)
                                .addComponent(jLabel6)
                                .addComponent(txtFecha))
                            .addComponent(cmdBuscarCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(txtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(txtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)
                            .addComponent(txtGuia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(cmdAgregar)
                                .addComponent(txtPrecio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel11)
                                .addComponent(txtCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel10)
                                .addComponent(txtProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel18)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel9)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel12)
                            .addComponent(txtSubtotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmdQuitar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel13)
                            .addComponent(txtDescuento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel17))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtSubtotalD, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel14)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmdGuardar)
                        .addComponent(jButton3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel15)
                    .addComponent(txtIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel16)
                        .addComponent(jButton2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(lblUsuario))
        );

        setSize(new java.awt.Dimension(809, 724));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void txtCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCedulaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCedulaActionPerformed

    private void txtClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtClienteActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtClienteActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 10) {

            CSelecciones.articulo = am.buscarPorCodigo(txtCodigo.getText());

            if (CSelecciones.articulo == null) {
                JOptionPane.showMessageDialog(rootPane, "No se encontro el artículo", "Error", JOptionPane.ERROR_MESSAGE);
            } else {
                txtPrecio.setText(CSelecciones.articulo.getPVenta().toString());
                txtProducto.setText(CSelecciones.articulo.getDescripcion()+" "+CSelecciones.articulo.getMarca()+" "+CSelecciones.articulo.getModelo());
            }
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        CSelecciones.texto1 = txtCodigo;
        CSelecciones.texto2 = txtPrecio;
        CSelecciones.texto3=txtProducto;
        new VSeleccionArticulo(true).setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cmdAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdAgregarActionPerformed
        // TODO add your handling code here:
        if (CSelecciones.articulo != null) {
            double precio = 0;
            try {
                precio = Double.parseDouble(txtPrecio.getText()) / (1 + configuraciones.getInstance().getConfiguracion().getIva() / 100d);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Campo precio incorrecto", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (CSelecciones.articulo.getStock() < Integer.parseInt(String.valueOf(txtCantidad.getValue()))) {
                JOptionPane.showMessageDialog(rootPane, "No existen sufucientes artículos en stock");
                return;
            }

            agregarArticulo(precio, Integer.parseInt(String.valueOf(txtCantidad.getValue())));

            limpiaTodo();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un artículo", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_cmdAgregarActionPerformed

    private void txtDescuentoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_txtDescuentoStateChanged
        // TODO add your handling code here:
        Calcular();
    }//GEN-LAST:event_txtDescuentoStateChanged

    private void cmdQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdQuitarActionPerformed
        // TODO add your handling code here:

        if (dtgFactura.getSelectedRow() != -1) {
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro", "Quitar Articulo", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                int i = dtgFactura.getSelectedRow();
                modelo.removeRow(i);
                factura.getDetallefacturaList().remove(i);
                Calcular();
            }

        } else {
            JOptionPane.showMessageDialog(rootPane, "Primero Seleccione un articulo", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdQuitarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        // TODO add your handling code here:
        if (factura.getDetallefacturaList().size() > 0) {
            try {
                factura.setNumero(Integer.parseInt(txtNumero.getText()));
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, "Ingrese un número de factura", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (JOptionPane.showConfirmDialog(rootPane, "Esta seguro de guardar la factura?", "Guardar Factura", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                factura.setIdusuario(configuraciones.getInstance().getUsuario());
                factura.setCedulaCliente(CSelecciones.cliente);
                factura.setFecha(d);
                factura.setEstado(0);
                factura.setGuiaRemision(txtGuia.getText());
                FacturaManager fm = new FacturaManager();
                fm.guardarFactura(factura);
                if (JOptionPane.showConfirmDialog(rootPane, "Factura guardada correctamente\nDesea imprimirla?", "Imprimir Factura", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                    //new CImprimir().imprimirFactura(factura);
                }
                limpiaFactura();
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "No ha registrado artículos a vener", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void limpiaFactura()
    {
        CSelecciones.cliente=null;
        CSelecciones.articulo=null;
        factura= new Factura();
        factura.setDetallefacturaList(new ArrayList());
        txtNumero.setText("");
        txtCedula.setText("");
        txtCliente.setText("");
        txtDescuento.setValue(0);
        txtDireccion.setText("");
        txtGuia.setText("");
        txtIVA.setText("");
        txtSubtotal.setText("");
        txtSubtotalD.setText("");
        txtTelefono.setText("");
        txtTotal.setText("");
        for(int i=modelo.getRowCount()-1; i>=0;i--)
        {
            modelo.removeRow(i);
        }
    }
    private void txtNumeroKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNumeroKeyReleased
        // TODO add your handling code here:
        Validacion validar = new Validacion();
        validar.numeros(evt, txtNumero);
    }//GEN-LAST:event_txtNumeroKeyReleased

    private void txtCodigoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyReleased
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoKeyReleased

    private void txtPrecioKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioKeyReleased
        // TODO add your handling code here:
        Validacion validar = new Validacion();
        validar.decimal(evt, txtPrecio);
    }//GEN-LAST:event_txtPrecioKeyReleased

    private void txtNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNumeroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtNumeroActionPerformed

    private void txtCodigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCodigoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCodigoActionPerformed

    private void mnuQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuQuitarActionPerformed
        // TODO add your handling code here:
        cmdQuitar.doClick();
    }//GEN-LAST:event_mnuQuitarActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        VMantenimientoCliente.getInstance().show();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void mnuManArticulosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuManArticulosActionPerformed
        // TODO add your handling code here:
        VMantenimientoArticulos.getInstance().show();
    }//GEN-LAST:event_mnuManArticulosActionPerformed

    private void mnuManProveedoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuManProveedoresActionPerformed
        // TODO add your handling code here:
        VMantenimientoProveedores.getInstance().setVisible(true);
    }//GEN-LAST:event_mnuManProveedoresActionPerformed

    private void mnuAjustesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuAjustesActionPerformed
        // TODO add your handling code here:
        new VConfiguracionSis().show();
    }//GEN-LAST:event_mnuAjustesActionPerformed

    private void mnuUsuariosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuUsuariosActionPerformed
        // TODO add your handling code here:
        if (configuraciones.getInstance().getUsuario().getRol() != 2) {
            new VUsuarios().show();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Solo los administradores pueden gestionar los usuarios");
        }
    }//GEN-LAST:event_mnuUsuariosActionPerformed

    private void mnuReindexarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuReindexarActionPerformed
        // TODO add your handling code here:
        try {
            new GenericController().indexarPrimeraVez();
            JOptionPane.showMessageDialog(rootPane, "Completado");
        } catch (Exception e) {
        }
    }//GEN-LAST:event_mnuReindexarActionPerformed

    private void mnuRespaldarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRespaldarActionPerformed
        // TODO add your handling code here:
        String path;
        Date d = new Date();

        String fecha = d.getDate() + "_" + (d.getMonth() + 1) + "_" + (d.getYear() + 1900);
        path = "C:/facturacion/bd" + fecha + ".sql";
        
        if (new DBRestore().backupDB(configuraciones.getInstance().getConfiguracion().getPathBase(), "celulares", "root", configuraciones.getInstance().getConfiguracion().getClaveBase(), path)) {
            JOptionPane.showMessageDialog(rootPane, "Completado");
        } else {
            JOptionPane.showMessageDialog(rootPane, "No se pudo respaldar la base de datos");
        }
    }//GEN-LAST:event_mnuRespaldarActionPerformed

    private void mnuRepVentasFechasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRepVentasFechasActionPerformed
        // TODO add your handling code here:
        new VBuscarVentasFecha().show();
    }//GEN-LAST:event_mnuRepVentasFechasActionPerformed

    private void cmdBuscarFacturaFechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarFacturaFechaActionPerformed
        // TODO add your handling code here:
        new VBuscarFacturaFecha().show();
    }//GEN-LAST:event_cmdBuscarFacturaFechaActionPerformed

    private void mnuBuscarFacturaClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuBuscarFacturaClienteActionPerformed
        // TODO add your handling code here:
        String ced = JOptionPane.showInputDialog(rootPane, "Ingrese el numero de cedula o ruc del cliente a buscar", "Buscar Factura", JOptionPane.INFORMATION_MESSAGE);
        if (ced != null) {
            List<Factura> listaFacturas;
            listaFacturas=new FacturaManager().buscarPorCedula(ced);
            if (listaFacturas!=null&&listaFacturas.size() > 0) {
                new VBuscarPorCliente(listaFacturas).setVisible(true);
            } else {
                JOptionPane.showMessageDialog(rootPane, "No se han encontrado facturas de este cliente", "Buscar Factura", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }//GEN-LAST:event_mnuBuscarFacturaClienteActionPerformed

    private void mnuBuscarFacturaNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuBuscarFacturaNumeroActionPerformed
        // TODO add your handling code here:
        String num = JOptionPane.showInputDialog(rootPane, "Ingrese el numero de factura a buscar", "Buscar Factura", JOptionPane.INFORMATION_MESSAGE);
        if(num!=null)
        {
            int numero;
            try {
                numero = Integer.parseInt(num);

            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, "Ingrese un numero de Factura", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            FacturaManager fm = new FacturaManager();
            Factura factura =fm.buscarPorNumero(numero);
            if(factura!=null)
            {
                new VVerFactura(factura).show();
            }
            else
            {
                JOptionPane.showMessageDialog(rootPane, "No se encontró una factura con ese número", "Error", JOptionPane.ERROR_MESSAGE);
            }}
    }//GEN-LAST:event_mnuBuscarFacturaNumeroActionPerformed

    private void mnuStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuStockActionPerformed
        // TODO add your handling code here:
        new VSeleccionArticulo(2).setVisible(true);
    }//GEN-LAST:event_mnuStockActionPerformed

    private void mnuStockMinimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuStockMinimoActionPerformed
        // TODO add your handling code here:
        new VSeleccionArticulo(1).setVisible(true);
    }//GEN-LAST:event_mnuStockMinimoActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void cmdBuscarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarClienteActionPerformed
        // TODO add your handling code here:
        new VBuscarCliente().show();
    }//GEN-LAST:event_cmdBuscarClienteActionPerformed

    private void txtCedulaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCedulaKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode()==10)
        {
            cmdBuscar.doClick();
        }
    }//GEN-LAST:event_txtCedulaKeyPressed

    private void cmdBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBuscarActionPerformed
        // TODO add your handling code here:
        ClienteManager cm = new ClienteManager();
            CSelecciones.cliente=cm.buscarPorCedula(txtCedula.getText());
            if(CSelecciones.cliente==null)
            {
                new VNuevoCliente(txtCedula.getText(),cmdBuscar).show();
            }
            else
            {
                setDatos(CSelecciones.cliente.getCedula(), CSelecciones.cliente.getNombres(), CSelecciones.cliente.getApellidos(), CSelecciones.cliente.getDireccion(), CSelecciones.cliente.getTelefono());
            }
    }//GEN-LAST:event_cmdBuscarActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        limpiaFactura();
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
     * @param args the command line arguments
     */
    private void Calcular() {
        double subtotal = 0.0D;
        double iva = 0.0D;
        double desc = Double.parseDouble(String.valueOf(this.txtDescuento.getValue()));
        for (int i = 0; i < factura.getDetallefacturaList().size(); i++) {
            subtotal += factura.getDetallefacturaList().get(i).getCantidad() * factura.getDetallefacturaList().get(i).getPVenta();

            double sd = factura.getDetallefacturaList().get(i).getCantidad() * factura.getDetallefacturaList().get(i).getPVenta();
            sd = sd - sd * desc / 100.0D;
            iva += sd * configuraciones.getInstance().getConfiguracion().getIva() / 100.0D;
        }

        double subtd = subtotal - subtotal * desc / 100.0D;
        double total = subtd + iva;
        factura.setDescuento(desc);
        factura.setIva(iva);
        factura.setSubtotal(subtotal);
        factura.setTotal(total);
        this.txtSubtotal.setText(String.valueOf(CNumeros.redondear(subtotal)));
        this.txtSubtotalD.setText(String.valueOf(CNumeros.redondear(subtd)));
        this.txtIVA.setText(String.valueOf(CNumeros.redondear(iva)));
        this.txtTotal.setText(String.valueOf(CNumeros.redondear(total)));
    }

    private void limpiaTodo() {
        CSelecciones.articulo = null;
        txtPrecio.setText("");
        txtCodigo.setText("");
        txtProducto.setText("");
        txtCantidad.setValue(1);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            System.out.println("Error setting native LAF: " + e);
        }
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VPrincipal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdAgregar;
    private javax.swing.JButton cmdBuscar;
    private javax.swing.JButton cmdBuscarCliente;
    private javax.swing.JMenuItem cmdBuscarFacturaFecha;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdQuitar;
    private javax.swing.JTable dtgFactura;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblDireccion;
    private javax.swing.JLabel lblLocal;
    private javax.swing.JLabel lblUsuario;
    private javax.swing.JPopupMenu mnuAcciones;
    private javax.swing.JMenuItem mnuAjustes;
    private javax.swing.JMenuItem mnuBuscarFacturaCliente;
    private javax.swing.JMenuItem mnuBuscarFacturaNumero;
    private javax.swing.JMenu mnuFacturas;
    private javax.swing.JMenuItem mnuManArticulos;
    private javax.swing.JMenuItem mnuManProveedores;
    private javax.swing.JMenu mnuMantenimientos;
    private javax.swing.JMenuItem mnuQuitar;
    private javax.swing.JMenuItem mnuReindexar;
    private javax.swing.JMenuItem mnuRepVentasFechas;
    private javax.swing.JMenu mnuReportes;
    private javax.swing.JMenuItem mnuRespaldar;
    private javax.swing.JMenu mnuSistema;
    private javax.swing.JMenuItem mnuStock;
    private javax.swing.JMenuItem mnuStockMinimo;
    private javax.swing.JMenuItem mnuUsuarios;
    private javax.swing.JSpinner txtCantidad;
    private javax.swing.JTextField txtCedula;
    private javax.swing.JTextField txtCliente;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JSpinner txtDescuento;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtGuia;
    private javax.swing.JTextField txtIVA;
    private javax.swing.JTextField txtNumero;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtProducto;
    private javax.swing.JTextField txtSubtotal;
    private javax.swing.JTextField txtSubtotalD;
    private javax.swing.JTextField txtTelefono;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables

    private void agregarArticulo(double precio, int cantidad) {
        boolean existe = false;
            for (int i = 0; i < factura.getDetallefacturaList().size(); i++) {

                if (factura.getDetallefacturaList().get(i).getIdArticulo().equals(CSelecciones.articulo) && factura.getDetallefacturaList().get(i).getPVenta() == precio) {
                    existe = true;
                    int nuevaCant = factura.getDetallefacturaList().get(i).getCantidad() + cantidad;
                    if (nuevaCant > CSelecciones.articulo.getStock()) {

                        JOptionPane.showMessageDialog(rootPane, "No existen suficientes artículos en Stock", "Error", JOptionPane.ERROR_MESSAGE);
                        limpiaTodo();
                        return;
                    }
                    factura.getDetallefacturaList().get(i).setCantidad(nuevaCant);
                    dtgFactura.setValueAt(nuevaCant, i, 0);
                    dtgFactura.setValueAt(CNumeros.redondear(precio * nuevaCant), i, 3);
                    Calcular();

                    break;
                }
            }
        
        if (!existe) {
            Detallefactura detallefactura = new Detallefactura();
            detallefactura.setCantidad(cantidad);
            detallefactura.setIdArticulo(CSelecciones.articulo);
            detallefactura.setNumFactura(factura);
            detallefactura.setPVenta(precio);
            factura.getDetallefacturaList().add(detallefactura);
            String desc = detallefactura.getIdArticulo().getDescripcion() + " " + detallefactura.getIdArticulo().getMarca() + " " + detallefactura.getIdArticulo().getModelo();
            
            String[] producto = {detallefactura.getCantidad().toString(), desc, String.valueOf(CNumeros.redondear(precio)), String.valueOf(CNumeros.redondear(precio * cantidad))};
            modelo.addRow(producto);
            Calcular();

        }
    }
    public void setDatos(String cedula, String nombre, String apellido, String direccion, String telefono)
    {
        txtCedula.setText(cedula);
        txtCliente.setText(nombre+" "+apellido);
        txtDireccion.setText(direccion);
        txtTelefono.setText(telefono);
        
        
    }
}
